package org.scohen.juploadr.app.tags;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class TagParser {

    public static Set<Tag> parse(String input) {
        Set<Tag> tags = new LinkedHashSet<Tag>();
        if (input != null) {
            StringBuffer tag = new StringBuffer();

            boolean insideQuote = false;
            for (int i = 0; i < input.length(); i++) {
                char currentChar = input.charAt(i);
                
                if (currentChar == ' ') {
                    if (!insideQuote) {
                        tags.add(new Tag(tag.toString()));
                        tag.delete(0, tag.length());
                    } else {
                        tag.append(currentChar);
                    }
                } else if (currentChar == '"') {
                    if (insideQuote) {
                        tags.add(new Tag(tag.toString()));
                        tag.delete(0, tag.length());
                        if (i + 1 < input.length() && input.charAt(i + 1) == ' ') {
                            i++;
                        }
                    }
                    insideQuote = !insideQuote;
                } else {
                    tag.append(currentChar);
                }
            }
            tags.add(new Tag(tag.toString()));
        }
        return tags;
    }

    public static String toInputString(Set<Tag> tags) {
        StringBuffer sb = new StringBuffer();
        
        Iterator<Tag> iter = tags.iterator();
        while (iter.hasNext()) {
            sb.append(iter.next().toString());
            if (iter.hasNext()) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    public static String toRequestString(Set<Tag> tags) {
        return toInputString(tags);
    }

    public static void main(String[] args) {
        String tags ="tag1 tag2 tag3 tag4 tag5";
        System.out.println(TagParser.parse(tags));
        System.out.println(TagParser.toInputString(TagParser.parse(tags)));

    }

}
